package csu.web.credit_bank.mapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import csu.web.credit_bank.pojo.Course;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import csu.web.credit_bank.pojo.vo.SelectedCourseVO;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.Map;

@Repository
public interface CoursesMapper extends BaseMapper<Course> {

    @Select("""
            SELECT
                c.id, c.name, c.image, c.credit,
                u.username AS teacherName,
                t.avatar AS teacherAvatar
            FROM
                courses c
            JOIN course_selections cs ON c.id = cs.course_id
            JOIN users u ON c.teacher_id = u.id
            LEFT JOIN teachers t ON c.teacher_id = t.user_id
            WHERE
                cs.user_id = #{userId}
            """)
    IPage<SelectedCourseVO> selectSelectedCoursesByUserId(IPage<SelectedCourseVO> page, @Param("userId") String userId);

    @Select("""
            <script>
            SELECT
                c.id, c.name, c.description, c.credit, c.image, c.teacher_id,
                u.username AS teacherName
            FROM
                courses c
            LEFT JOIN
                users u ON c.teacher_id = u.id
            <where>
                <if test="q != null and q != ''">
                    (LOWER(c.name) LIKE CONCAT('%', LOWER(#{q}), '%')
                    OR LOWER(c.description) LIKE CONCAT('%', LOWER(#{q}), '%')
                    OR LOWER(u.username) LIKE CONCAT('%', LOWER(#{q}), '%'))
                </if>
            </where>
            <choose>
                <when test="sortBy == 'credit'">
                    ORDER BY c.credit DESC
                </when>
                <otherwise>
                    ORDER BY c.id DESC
                </otherwise>
            </choose>
            </script>
            """)
    IPage<Course> searchCourses(IPage<Course> page,
                                @Param("q") String q,
                                @Param("sortBy") String sortBy);

    @Select("""
            SELECT
                c.*,
                lp.progress_percent AS progressPercent
            FROM
                courses c
            JOIN
                course_selections cs ON c.id = cs.course_id
            LEFT JOIN
                learning_progress lp ON c.id = lp.course_id AND cs.student_id = lp.student_id
            WHERE
                cs.student_id = #{studentId}
            """)
    IPage<Map<String, Object>> findSelectedCoursesWithProgress(Page<Map<String, Object>> page, @Param("studentId") String studentId);

}